package cn.xing.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.xing.modules.app.entity.PaymentInfoEntity;
import cn.xing.modules.app.service.PaymentInfoService;
import cn.xing.modules.app.vo.PayVo;
import cn.xing.modules.sys.entity.RefundInfoEntity;
import cn.xing.modules.sys.service.RefundInfoService;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@ConfigurationProperties(prefix = "alipay")
@Component
@Data
@Slf4j
public class AlipayTemplate {

    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private RefundInfoService refundInfoService;
    //在支付宝创建的应用的id
    private String app_id = "2016092200568607";

    // 商户私钥，您的PKCS8格式RSA2私钥
    private String merchant_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCe7O4fChb+Flc6zgeONcIPqD7rEyaZnkCqMR0/kj9SDIVElYtrPLN3I4RqjQeiRI/2yub+ONUyU8Fi9lvrbB5bkcq6PTyDEzpzBjtjMsysxBsTlOZdbPxTjvhAXTmU5HIlegjQybVLHnnfo4d6/FQmwyxZOlsBzNVkp8c1cqVoWHVa3QSnXknkdMNPFAEdOJkUqdABRlBb5uClGuDESNTcT8/bwPQ+0wgO8KquFfaSxXSpf0dOwa7eYINFb6pjxyIhdXRFRlBBGu8P/OqwgW2haMFx3wVRFxeLiTvDFyHAn3u7pUxwaZdnQ2q572VFRF4yfB8xL3dK5J5eY4CU5l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zfC6EsWKp0CUcv8oMwM1uhMbDXo0NXsKvNu0utvq3I+WepYGWMufKu0+aoeetWzolONwOiaS3mPkN5IJm/gZavwHNcXTXNjQojh6uAa+ngdOrO5VJGmqBnQEQxE5smzqwVktSnHTxnK58a0ZL+2LLS0bigboU=";
    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    private String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoe34PoFnMX/nvTSCjkN38Z0b8UKwK5fN2RY0DAbUQ2C/4g58q74sDWoRSPBXjdqGoKIBtrr8TSQ5JwAc4anN+9VP1SXdP4EXfTZ1U8jk+ORk8P7ycZpEvZJefnCk+ef1fwXTxivxxprOBqsxrg+Ndxn9OErFnHN0Q43i3nHJsgvnU+AGFrLn3IXyYWqdj/1y5HjZr3Tad3Oh7SSUBsFEwUAjfZRZ+EzrszJ1L+KXe1sY56yeDkiL8AmodJXOJEg9NG8Saypt0z58ST/h2BuGO2mCEYz2X75y8ckLwnII2IIKlx+1MRAl4WCHxeABVIMlyy5IU0Q4rUxbWqpUeg3dWwIDAQAB";
    // 服务器[异步通知]页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
    private String notify_url;

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    //同步通知，支付成功，一般跳转到成功页
    // private String return_url;

    // 签名方式
    private String sign_type = "RSA2";

    // 字符编码格式
    private String charset = "utf-8";

    // 支付宝网关； https://openapi.alipaydev.com/gateway.do
    private String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    public String pay(PayVo vo,String paramReturnUrl) throws AlipayApiException {

        //AlipayClient alipayClient = new DefaultAlipayClient(AlipayTemplate.gatewayUrl, AlipayTemplate.app_id, AlipayTemplate.merchant_private_key, "json", AlipayTemplate.charset, AlipayTemplate.alipay_public_key, AlipayTemplate.sign_type);
        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = buildAlipayClient();

        //2、创建一个支付请求 //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(paramReturnUrl);
        alipayRequest.setNotifyUrl(notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = vo.getOut_trade_no();
        //付款金额，必填
        String total_amount = vo.getTotal_amount();
        //订单名称，必填
        String subject = vo.getSubject();
        //商品描述，可空
        String body = vo.getBody();

        //超时时间
        String timeout = "1m";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        System.out.println("支付宝的响应：" + result);

        return result;

    }

    /**
     * 退款
     *
     * @param orderSn
     * @param reason
     */
    public boolean refund(String orderSn, String reason) throws AlipayApiException {

        AlipayTradeRefundRequest refundRequest = new AlipayTradeRefundRequest();

        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();

        // 查询出 之前 支付的信息
        PaymentInfoEntity paymentInfo = paymentInfoService.queryByOrderSn(orderSn);
        BigDecimal totalAmount = paymentInfo.getTotalAmount();
        String refundSn = "R" + id;
        model.setOutTradeNo(orderSn);
        // model.setTradeNo(trade_no);
        model.setRefundAmount(totalAmount.toString());
        model.setRefundReason(reason);
        model.setOutRequestNo(refundSn);
        refundRequest.setBizModel(model);

        AlipayClient client = buildAlipayClient();
        AlipayTradeRefundResponse refundResponse = client.execute(refundRequest);
        boolean refundSuccess = refundResponse.isSuccess();
        String errorReason = refundResponse.getSubMsg();
        log.info("支付宝退款[{}]，消息[{}],结果[{}]", orderSn, errorReason, JSON.toJSONString(refundResponse));

        // 保存退款记录，特别是退款结果
        RefundInfoEntity refundInfoEntity = new RefundInfoEntity();
        refundInfoEntity.setOrderSn(orderSn);
        refundInfoEntity.setRefundFee(totalAmount);
        refundInfoEntity.setRefundSn(refundSn);
        refundInfoEntity.setReason(reason);
        if (refundSuccess) {
            // 退款成功
            refundInfoEntity.setRefundStatus(1);
            refundInfoEntity.setFailedReason("");
        } else {
            refundInfoEntity.setRefundStatus(0);
            refundInfoEntity.setFailedReason(errorReason);
        }

        refundInfoService.save(refundInfoEntity);

        return refundSuccess;
    }


    public String wapPay(PayVo vo,String paramReturnUrl) throws AlipayApiException {
        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = buildAlipayClient();

        //2、创建一个支付请求 //设置请求参数
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        alipayRequest.setReturnUrl(paramReturnUrl);
        alipayRequest.setNotifyUrl(notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = vo.getOut_trade_no();
        //付款金额，必填
        String total_amount = vo.getTotal_amount();
        //订单名称，必填
        String subject = vo.getSubject();
        //商品描述，可空
        String body = vo.getBody();

        //超时时间
        String timeout = "1m";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout + "\","
                + "\"product_code\":\"QUICK_WAP_WAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        System.out.println("支付宝的响应：" + result);

        return result;
    }

    public AlipayClient buildAlipayClient() {
        return new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, alipay_public_key, sign_type);
    }
}
